<template>
	<view class="jiejiu-container" @refresh="onPullDownRefresh">
			<!-- 借酒总览 -->
			<view
		
		style="
			background-color: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
		"
	>
		<!-- 标题 -->
		<view
			style="
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				text-align: center;
				margin-bottom: 20rpx;
			"
		>
			借酒总览
		</view>

		<!-- 每种酒的总数 -->
		<view
			class="total-item"
			v-for="(quantity, wineName) in totalBorrowQuantities"
			:key="wineName"
			style="
				display: flex;
				justify-content: space-between;
				padding: 15rpx 0;
				border-bottom: 1rpx solid #eee;
			"
		>
			<text
				style="
					font-size: 30rpx;
					color: #666;
					font-weight: bold;
				"
			>{{ wineName }}:</text>
			<text
				style="
					font-size: 30rpx;
					color: #007aff;
					font-weight: bold;
				"
			>{{ quantity }} 瓶</text>
		</view>

		<!-- 无记录提示 -->
		<view
			v-if="Object.keys(totalBorrowQuantities).length === 0"
			style="
				text-align: center;
				color: #999;
				font-size: 28rpx;
				padding: 20rpx 0;
			"
		>
			暂无借酒记录
		</view>
	</view>
		<!-- 借酒表单 - 仅吧员可见 -->
		<view v-if="isBayuan" class="borrow-wine-section">
			<view class="section-title">新增借酒记录</view>
			<view class="form-item">
				<text class="label">业务经理/管理层:</text>
				<picker 
					mode="selector" 
					:range="businessManagers" 
					range-key="userName"
					:value="businessManagers.findIndex(item => item.userId === borrowForm.userId)"
					@change="handleManagerChange"
					class="picker"
				>
					<view class="picker-text">{{ borrowForm.userName || '请选择业务经理/管理层' }}</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="label">酒的种类:</text>
				<picker 
					mode="selector" 
					:range="wineTypes" 
					:value="wineTypeIndex"
					@change="handleWineTypeChange"
					class="picker"
				>
					<view class="picker-text">{{ selectedWineType || '请选择酒的种类' }}</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="label">借酒数量:</text>
				<input 
					class="input" 
					type="number" 
					v-model="borrowQuantity" 
					placeholder="请输入借酒数量" 
				/>
			</view>
			<view class="form-item">
				<text class="label">房间名称:</text>
				<view class="room-search-container">
					<input 
						class="room-search-input" 
						type="text" 
						v-model="borrowForm.roomSearchText" 
						placeholder="请输入房间名称搜索" 
						@input="handleRoomSearch"
					/>
					<button class="room-search-btn" @click="searchRooms">搜索</button>
				</view>
			</view>
			
			<!-- 搜索结果显示 -->
			<view v-if="borrowForm.roomSearchText && filteredRoomList.length === 0" class="form-item">
				<text class="no-results">未找到匹配的房间</text>
			</view>
			
			<view v-if="filteredRoomList.length > 0" class="form-item">
				<text class="label">选择房间:</text>
				<picker 
					mode="selector" 
					:range="filteredRoomList" 
					range-key="cc"
					:value="filteredRoomList.findIndex(item => item.id === borrowForm.selectedRoomId)"
					@change="handleRoomNameChange"
					class="picker"
				>
					<view class="picker-text">{{ borrowForm.roomName || '请选择房间' }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="label">借酒日期:</text>
				<picker mode="date" v-model="borrowForm.storageDate" @change="handleDateChange" class="picker">
					<view class="picker-text">{{ borrowForm.storageDate || '请选择借酒日期' }}</view>
				</picker>
			</view>
			<button class="confirm-borrow-btn" @click="handleBorrow" :disabled="!isBorrowFormValid">确认借酒</button>
		</view>

	

		<!-- 查询存酒记录 -->
		<view class="search-section">
			<view class="search-title">查询借酒记录</view>
			<view class="search-item">
				<text class="search-label">房间名称</text>
				<input 
					class="search-input" 
					type="text" 
					v-model="searchForm.roomName" 
					placeholder="请输入房间名称"
				/>
			</view>
			<view class="search-item">
				<text class="search-label">日期</text>
				<picker 
					mode="date" 
					:value="searchForm.date" 
					@change="handleSearchDateChange"
					class="date-picker"
				>
					<view class="picker-text">{{ searchForm.date || '请选择日期' }}</view>
				</picker>
			</view>
			<view class="search-buttons">
				<button class="search-btn" @click="handleSearch">搜索</button>
				<button class="reset-btn" @click="handleReset">重置</button>
			</view>
		</view>

		<!-- 借酒记录列表 -->
		<view class="borrow-list">
			<view class="section-title">{{ isBayuan ? '借酒记录' : '我的借酒记录' }}</view>
			<view class="borrow-item" v-for="(item, index) in borrowList" :key="index">
				<view class="item-header">
					<view class="manager"> {{ item.userName }}</view>
					<!-- <view class="wine">酒名: {{ item.wineName }}</view> -->
					<!-- <view class="quantity">数量: {{ item.quantity }}</view> -->
					<view class="room">房间: {{ item.roomName || item.roomId }}</view>
				</view>
				<view class="item-body">
					<view class="info-row">
						<text class="label">借酒信息:</text>
						<view class="wine-info">
							<text class="wine-type">{{ getWineType(item.myBorrow) }}</text>
							<view class="quantity-edit">
								<text class="quantity-text">{{ getWineQuantity(item.myBorrow) }}</text>
								<text class="unit">瓶</text>
							</view>
						</view>
					</view>
					<view class="info-row">
						<text class="label">借酒日期:</text>
						<text class="value">{{ item.storageDate ? formatDate(item.storageDate) : '暂无' }}</text>
					</view>
					<button 
						v-if="isBayuan"
						class="edit-btn" 
						@click="showReturnWinePopup(item)"
						hover-class="edit-btn-hover"
					>
						还酒/删除
					</button>
				</view>
			</view>
			
			<view v-if="loading" class="loading">加载中...</view>
			<view v-else-if="borrowList.length === 0" class="no-data">暂无借酒记录</view>
		</view>

		<!-- 编辑弹窗 - 仅吧员可见 -->
		<uni-popup v-if="isBayuan" ref="editPopup" type="dialog">
			<uni-popup-dialog
				title="编辑借酒记录"
				:before-close="true"
				@confirm="confirmEdit"
				@close="closeEdit"
			>
				<view class="edit-form">
					<view class="form-item">
						<text class="label">业务经理/管理层:</text>
						<text class="value">{{ editForm.userName }}</text>
					</view>
					<view class="form-item">
						<text class="label">借酒数量:</text>
						<input 
							class="input" 
							type="number" 
							v-model="editForm.myBorrow" 
							placeholder="请输入借酒数量" 
						/>
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>

		<!-- 还酒/删除弹窗 - 仅吧员可见 -->
		<uni-popup v-if="isBayuan" ref="returnWinePopup" type="dialog">
			<uni-popup-dialog
				title="还酒/删除记录"
				:before-close="true"
				@confirm="confirmReturnWine"
				@close="closeReturnWine"
			>
				<view class="return-wine-form">
					<view class="form-item">
						<text class="label">借酒人:</text>
						<text class="value">{{ returnWineForm.userName }}</text>
					</view>
					<view class="form-item">
						<text class="label">酒的种类:</text>
						<text class="value">{{ getWineType(returnWineForm.myBorrow) }}</text>
					</view>
					<view class="form-item">
						<text class="label">房间名称:</text>
						<text class="value">{{ returnWineForm.roomName || '未知房间' }}</text>
					</view>
					<view class="form-item">
						<text class="label">原借数量:</text>
						<text class="value">{{ getWineQuantity(returnWineForm.myBorrow) }} 瓶</text>
					</view>
					<view class="form-item">
						<text class="label">还酒数量:</text>
						<input 
							class="input" 
							type="number" 
							v-model="returnWineForm.returnQuantity" 
							placeholder="请输入还酒数量" 
						/>
					</view>
					<view class="form-item">
						<text class="label">操作类型:</text>
						<picker 
							mode="selector" 
							:range="operationTypes" 
							:value="returnWineForm.operationTypeIndex"
							@change="handleOperationTypeChange"
							class="picker"
						>
							<view class="picker-text">{{ operationTypes[returnWineForm.operationTypeIndex] }}</view>
						</picker>
					</view>

				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import { listUsersByRole } from '@/api/system/user'
	import { listWine, addWine, updateWine, delWine } from '@/api/system/wine'
	import { getRoom, listRoom } from '@/api/system/room'
	
	export default {
		data() {
			return {
				borrowList: [],
				loading: false,
				businessManagers: [], // 业务经理/管理层列表
				isBayuan: false, // 吧员角色标识
				isBusinessManager: false, // 业务经理/管理层角色标识
				currentUserId: null, // 当前用户ID
				borrowForm: {
					userId: null,
					userName: '',
					myBorrow: '',
					status: '待归还',
					roomId: null,
					roomName: '',
					storageDate: '',
					selectedRoomId: '', // 新增：选中的房间ID
					roomSearchText: '' // 新增：房间搜索文本
				},
				editForm: {
					id: null,
					userId: null,
					userName: '',
					myBorrow: '',
					storageDate: ''
				},
				returnWineForm: {
					id: null,
					userId: null,
					userName: '',
					myBorrow: '',
					roomName: '', // 添加房间名称
					returnQuantity: '',
					operationTypeIndex: 0 // 0: 还酒, 1: 删除
				},
				operationTypes: ['还酒', '删除记录'],
				wineTypes: [
					// 啤酒类
					'1664', '百威铝罐', '青岛铝罐', '科罗娜', '喜力铝罐', '百威听装',
					// 白兰地类
					'至尊', '路易十三', '马爹利尚选', '奥创', '马爹利XO', '人头马XO', '轩尼诗XO', '蓝带马爹利', '马爹利名仕', '轩尼诗VSOP',
					// 威士忌类
					'皇家礼炮', '芝华士12年', '黑方', '杰克丹尼', '麦卡伦12年',
					// 红酒类
					'威龙国际干白', '威龙国际干红', '卡斯特', '威龙有机干红', '威龙有机干白', '青稞干红', '青稞干白', '香槟'
				],
				wineTypeIndex: -1,
				selectedWineType: '',
				borrowQuantity: '',
				// 查询表单
				searchForm: {
					roomName: '',
					date: ''
				},
				allBorrowList: [], // 存储所有借酒记录，用于筛选
				roomList: [], // 房间列表
				filteredRoomList: [], // 过滤后的房间列表
			}
		},
		computed: {
			isBorrowFormValid() {
				const isValid = this.borrowForm.userId && this.selectedWineType && this.borrowQuantity && this.borrowForm.roomId && this.borrowForm.storageDate
				console.log('表单验证状态:', {
					userId: this.borrowForm.userId,
					selectedWineType: this.selectedWineType,
					borrowQuantity: this.borrowQuantity,
					roomId: this.borrowForm.roomId,
					storageDate: this.borrowForm.storageDate,
					isValid: isValid
				})
				return isValid
			},
			// 计算借酒总数
			totalBorrowQuantities() {
				const totals = {}
				this.borrowList.forEach(item => {
					if (item.myBorrow) {
						const wineType = this.getWineType(item.myBorrow)
						const quantity = parseInt(this.getWineQuantity(item.myBorrow)) || 0
						if (wineType && quantity > 0) {
							totals[wineType] = (totals[wineType] || 0) + quantity
						}
					}
				})
				return totals
			}
		},
		onLoad() {
			// 获取用户角色和ID
			const roles = uni.getStorageSync('roles')
			const userInfo = uni.getStorageSync('userInfo')
			this.isBayuan = roles && roles.includes('bayuan')
			this.isBusinessManager = roles && (roles.includes('yewujinli') || roles.includes('guanliceng'))
			this.currentUserId = userInfo?.user?.userId
			
			if (this.isBayuan) {
				this.getBusinessManagers() // 如果是吧员，获取业务经理/管理层列表
			}
			this.getRoomList() // 获取房间列表
			this.getBorrowList()
		},
		onPullDownRefresh() {
			// 刷新数据
			Promise.all([
				this.isBayuan ? this.getBusinessManagers() : Promise.resolve(),
				this.getBorrowList()
			]).finally(() => {
				uni.stopPullDownRefresh();
			});
		},
		methods: {
			// 获取业务经理和管理层列表
			async getBusinessManagers() {
				try {
					// 分别获取管理层（角色ID 104）和业务经理（角色ID 105）的人员
					const [managementRes, businessRes] = await Promise.all([
						listUsersByRole(104, null, 1, 1000), // 获取管理层，传递分页参数
						listUsersByRole(105, null, 1, 1000)  // 获取业务经理，传递分页参数
					])
					
					// 合并两个结果
					const managementUsers = managementRes.code === 200 ? (managementRes.rows || []) : []
					const businessUsers = businessRes.code === 200 ? (businessRes.rows || []) : []
					
					// 合并并去重（根据userId去重）
					const allUsers = [...managementUsers, ...businessUsers]
					const uniqueUsers = allUsers.filter((user, index, self) => 
						index === self.findIndex(u => u.userId === user.userId)
					)
					
					this.businessManagers = uniqueUsers
					
					// 检查是否有错误
					if (managementRes.code !== 200) {
						console.error('获取管理层列表失败:', managementRes.msg)
					}
					if (businessRes.code !== 200) {
						console.error('获取业务经理列表失败:', businessRes.msg)
					}
					
				} catch (error) {
					console.error('获取业务经理和管理层列表失败:', error)
					this.$modal.msgError('获取业务经理和管理层列表失败')
				}
			},
			
			// 处理业务经理/管理层选择
			handleManagerChange(e) {
				const selectedManager = this.businessManagers[e.detail.value]
				if (selectedManager) {
					this.borrowForm.userId = selectedManager.userId
					this.borrowForm.userName = selectedManager.userName
				}
			},
			
			// 处理酒的种类选择
			handleWineTypeChange(e) {
				this.wineTypeIndex = e.detail.value
				this.selectedWineType = this.wineTypes[this.wineTypeIndex]
			},
			
			// 获取房间列表
			async getRoomList() {
				try {
					const res = await listRoom()
					if (res.code === 200) {
						this.roomList = res.rows || []
						this.filteredRoomList = this.roomList // 初始化时也显示所有房间
					} else {
						console.error('获取房间列表失败:', res.msg)
					}
				} catch (error) {
					console.error('获取房间列表失败:', error)
				}
			},
			
			// 处理房间搜索输入
			handleRoomSearch() {
				// 实时搜索，不需要点击搜索按钮
				this.searchRooms()
			},
			
			// 搜索房间
			async searchRooms() {
				const searchText = this.borrowForm.roomSearchText.trim()
				if (!searchText) {
					this.filteredRoomList = this.roomList
					return
				}
				
				// 前端模糊搜索实现
				this.filteredRoomList = this.roomList.filter(room => 
					room.cc && room.cc.toLowerCase().includes(searchText.toLowerCase())
				)
				
				console.log('房间搜索:', {
					searchText,
					totalRooms: this.roomList.length,
					filteredRooms: this.filteredRoomList.length,
					results: this.filteredRoomList.map(r => r.cc)
				})
			},
			
			// 处理房间名称选择
			handleRoomNameChange(e) {
				const selectedRoom = this.filteredRoomList[e.detail.value]
				if (selectedRoom) {
					this.borrowForm.roomName = selectedRoom.cc
					this.borrowForm.roomId = selectedRoom.id
					this.borrowForm.selectedRoomId = selectedRoom.id
				}
			},
			
			// 处理借酒
			async handleBorrow() {
				// 校验房间
				if (!this.borrowForm.roomId) {
					this.$modal && this.$modal.msgError ? this.$modal.msgError('请选择房间') : alert('请选择房间');
					return;
				}
				
				if (!this.selectedWineType || !this.borrowQuantity) {
					uni.showToast({
						title: '请选择酒的种类并输入数量',
						icon: 'none'
					})
					return
				}
				
				if (!this.borrowForm.storageDate) {
					this.$modal && this.$modal.msgError ? this.$modal.msgError('请选择借酒日期') : alert('请选择借酒日期');
					return;
				}
				
				// Combine wine type and quantity into myBorrow field
				this.borrowForm.myBorrow = `${this.selectedWineType} ${this.borrowQuantity}瓶`
				
				try {
					const dataToSubmit = {
						...this.borrowForm,
						storageDate: this.borrowForm.storageDate,
						myBorrow: this.borrowForm.myBorrow, // 直接使用 myBorrow 字段
						quantity: 0, // 借酒记录 quantity 设为 0
						roomId: this.borrowForm.roomId,
						roomName: this.borrowForm.roomName, // 使用用户选择的房间名称
						wineName: '借酒', // 设置默认酒名
						
					}
					
					const res = await addWine(dataToSubmit)
					if (res.code === 200) {
						this.$modal.msgSuccess('借酒记录添加成功')
						// 清空表单
						this.borrowForm = {
							userId: null,
							userName: '',
							myBorrow: '',
							status: '待归还',
							roomId: null,
							roomName: '',
							storageDate: '',
							selectedRoomId: '',
							roomSearchText: ''
						}
						// 清空其他相关字段
						this.selectedWineType = ''
						this.wineTypeIndex = -1
						this.borrowQuantity = ''
						// 刷新列表
						this.getBorrowList()
					} else {
						this.$modal.msgError(res.msg || '借酒记录添加失败')
					}
				} catch (error) {
					console.error('添加借酒记录失败:', error)
					this.$modal.msgError('添加借酒记录失败')
				}
			},
			
			// 获取借酒列表
			async getBorrowList() {
				this.loading = true
				try {
					const queryParams = {
						pageNum: 1,
						pageSize: 50
					}
					const res = await listWine(queryParams)
					if (res.code === 200) {
						let filteredList = (res.rows || [])
							.filter(item => item.wineName === '借酒' && item.myBorrow !== null && item.myBorrow !== '')
						
						// 如果是业务经理或管理层，只显示自己的借酒记录
						if (this.isBusinessManager && this.currentUserId) {
							filteredList = filteredList.filter(item => item.userId === this.currentUserId)
						}
						
						// 直接反转顺序
						filteredList.reverse()
						
						// 保存所有记录用于筛选
						this.allBorrowList = filteredList.map(item => ({
							...item,
							borrowDate: item.storageDate
						}))
						
						// 应用筛选
						this.applySearchFilter()
					} else {
						this.$modal.msgError(res.msg || '获取借酒记录失败')
					}
				} catch (error) {
					console.error('获取借酒记录失败:', error)
					this.$modal.msgError('获取借酒记录失败')
				} finally {
					this.loading = false
				}
			},
			
			// 应用搜索筛选
			applySearchFilter() {
				let filteredList = [...this.allBorrowList]
				
				// 房间名称筛选
				if (this.searchForm.roomName) {
					filteredList = filteredList.filter(item => 
						item.roomName && item.roomName.includes(this.searchForm.roomName)
					)
				}
				
				// 日期筛选
				if (this.searchForm.date) {
					filteredList = filteredList.filter(item => 
						item.storageDate && item.storageDate.startsWith(this.searchForm.date)
					)
				}
				
				this.borrowList = filteredList
			},
			
			// 处理搜索
			handleSearch() {
				this.applySearchFilter()
			},
			
			// 处理重置
			handleReset() {
				this.searchForm = {
					roomName: '',
					date: ''
				}
				this.borrowList = [...this.allBorrowList]
			},
			
			// 处理搜索日期变化
			handleSearchDateChange(e) {
				this.searchForm.date = e.detail.value
			},
			
			formatDate(dateStr) {
				if (!dateStr) return '暂无'
				const date = new Date(dateStr)
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			},

			// 显示还酒/删除弹窗
			showReturnWinePopup(item) {
				this.returnWineForm = {
					id: item.id,
					userId: item.userId,
					userName: item.userName,
					myBorrow: item.myBorrow,
					roomName: item.roomName, // 添加房间名称
					returnQuantity: this.getWineQuantity(item.myBorrow), // 默认填入原借数量
					operationTypeIndex: 0 // 默认选择还酒
				}
				this.$refs.returnWinePopup.open()
			},

			// 处理操作类型选择
			handleOperationTypeChange(e) {
				this.returnWineForm.operationTypeIndex = e.detail.value
			},

			// 确认还酒/删除操作
			async confirmReturnWine() {
				const { returnQuantity, operationTypeIndex } = this.returnWineForm
				
				if (!returnQuantity || parseInt(returnQuantity) < 0) {
					this.$modal.msgError('请输入有效的还酒数量')
					return
				}

				const originalQuantity = parseInt(this.getWineQuantity(this.returnWineForm.myBorrow))
				const returnQty = parseInt(returnQuantity)

				if (returnQty > originalQuantity) {
					this.$modal.msgError('还酒数量不能超过原借数量')
					return
				}

				try {
					if (operationTypeIndex === 1) {
						// 删除记录
						const res = await this.deleteWineRecord(this.returnWineForm.id)
						if (res.code === 200) {
							this.$modal.msgSuccess('借酒记录已删除')
							// 从列表中移除
							this.borrowList = this.borrowList.filter(i => i.id !== this.returnWineForm.id)
							this.allBorrowList = this.allBorrowList.filter(i => i.id !== this.returnWineForm.id)
							this.closeReturnWine()
						} else {
							this.$modal.msgError(res.msg || '删除借酒记录失败')
						}
					} else {
						// 还酒操作
						const remainingQuantity = originalQuantity - returnQty
						const wineType = this.getWineType(this.returnWineForm.myBorrow)
						
						if (remainingQuantity === 0) {
							// 全部还完，删除记录
							const res = await this.deleteWineRecord(this.returnWineForm.id)
							if (res.code === 200) {
								this.$modal.msgSuccess('借酒记录已全部还完并删除')
								this.borrowList = this.borrowList.filter(i => i.id !== this.returnWineForm.id)
								this.allBorrowList = this.allBorrowList.filter(i => i.id !== this.returnWineForm.id)
								this.closeReturnWine()
							} else {
								this.$modal.msgError(res.msg || '删除借酒记录失败')
							}
						} else {
							// 部分还酒，更新记录
							const updatedMyBorrow = `${wineType} ${remainingQuantity}瓶`
							// 从原始记录中获取房间信息
							const originalRecord = this.borrowList.find(item => item.id === this.returnWineForm.id)
							const dataToSubmit = {
								id: this.returnWineForm.id,
								userId: this.returnWineForm.userId,
								userName: this.returnWineForm.userName,
								myBorrow: updatedMyBorrow,
								storageDate: this.returnWineForm.storageDate,
								quantity: 0,
								roomId: originalRecord ? originalRecord.roomId : 0,
								roomName: originalRecord ? originalRecord.roomName : '借酒记录',
								wineName: '借酒',
								aa: this.returnWineForm.remark // 将备注信息保存到aa字段
							}

							const res = await updateWine(dataToSubmit)
							if (res.code === 200) {
								this.$modal.msgSuccess(`已还酒 ${returnQty} 瓶，剩余 ${remainingQuantity} 瓶`)
								this.getBorrowList() // 刷新列表
								this.closeReturnWine()
							} else {
								this.$modal.msgError(res.msg || '还酒操作失败')
							}
						}
					}
				} catch (error) {
					console.error('还酒/删除操作失败:', error)
					this.$modal.msgError('操作失败')
				}
			},

			// 关闭还酒弹窗
			closeReturnWine() {
				this.returnWineForm = {
					id: null,
					userId: null,
					userName: '',
					myBorrow: '',
					roomName: '', // 重置房间名称
					returnQuantity: '',
					operationTypeIndex: 0
				}
				this.$refs.returnWinePopup.close()
			},



			// 确认编辑
			async confirmEdit() {
				if (!this.editForm.myBorrow || parseInt(this.editForm.myBorrow) <= 0) {
					this.$modal.msgError('请输入有效的借酒数量')
					return
				}

				try {
					// 从原始记录中获取房间信息
					const originalRecord = this.borrowList.find(item => item.id === this.editForm.id)
					const dataToSubmit = {
						...this.editForm,
						quantity: 0,
						roomId: originalRecord ? originalRecord.roomId : 0,
						roomName: originalRecord ? originalRecord.roomName : '借酒记录',
						wineName: '借酒'
					}

					const res = await updateWine(dataToSubmit)
					if (res.code === 200) {
						this.$modal.msgSuccess('借酒记录更新成功')
						this.getBorrowList()
					} else {
						this.$modal.msgError(res.msg || '借酒记录更新失败')
					}
				} catch (error) {
					console.error('更新借酒记录失败:', error)
					this.$modal.msgError('更新借酒记录失败')
				}
			},

			// 关闭编辑弹窗
			closeEdit() {
				this.editForm = {
					id: null,
					userId: null,
					userName: '',
					myBorrow: '',
					storageDate: ''
				}
			},

			// 从myBorrow中提取酒种类
			getWineType(myBorrow) {
				if (!myBorrow) return ''
				const match = myBorrow.match(/^(.+?)\s+\d+瓶$/)
				return match ? match[1] : myBorrow
			},
			
			// 从myBorrow中提取数量
			getWineQuantity(myBorrow) {
				if (!myBorrow) return ''
				const match = myBorrow.match(/(\d+)瓶$/)
				return match ? match[1] : ''
			},
			

			handleDateChange(e) {
				this.borrowForm.storageDate = e.detail.value
			},
			
			// 删除借酒记录
			async deleteWineRecord(id) {
				try {
					const res = await delWine(id)
					return res
				} catch (error) {
					console.error('删除借酒记录失败:', error)
					throw error
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
.jiejiu-container {
	padding: 20rpx;
	background-color: #f5f7fa;
	min-height: 100vh;
}

.borrow-wine-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 25rpx;

		.label {
			width: 160rpx;
			font-size: 30rpx;
			color: #555;
			flex-shrink: 0;
		}

		.input, .picker {
			flex: 1;
			height: 80rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 30rpx;
			background-color: #f5f7fa;
			box-sizing: border-box;
		}

		.room-search-container {
			display: flex;
			align-items: center;
			flex: 1;
			height: 80rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			background-color: #f5f7fa;

			.room-search-input {
				flex: 1;
				height: 100%;
				font-size: 28rpx;
				border: none;
				background-color: transparent;
			}

			.room-search-btn {
				height: 100%;
				line-height: 80rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				color: #409eff;
				background-color: transparent;
				border: none;
				border-left: 1rpx solid #dcdfe6;
			}
		}

		.picker-text {
			height: 80rpx;
			line-height: 80rpx;
			color: #333;
		}
		
		.no-results {
			font-size: 28rpx;
			color: #999;
			text-align: center;
			padding: 20rpx 0;
		}
	}

	.confirm-borrow-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #409eff;
		color: #fff;
		border-radius: 45rpx;
		font-size: 36rpx;
		margin-top: 40rpx;
		border: none;

		&:disabled {
			background-color: #a0cfff;
			cursor: not-allowed;
		}
	}
}

.borrow-list {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.borrow-item {
		background-color: #f8f9fa;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;

		.item-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15rpx;
			padding-bottom: 15rpx;
			border-bottom: 1rpx solid #eee;

			.manager {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.wine {
				font-size: 32rpx;
				color: #333;
			}

			.quantity {
				font-size: 32rpx;
				color: #333;
			}

			.room {
				font-size: 32rpx;
				color: #333;
				span {
				font-size: 28rpx;
				color: #666;
				}
			}
		}

		.item-body {
			position: relative;
			padding-bottom: 50rpx;

			.info-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 15rpx;
				padding-right: 0;

				.label {
					font-size: 28rpx;
					color: #666;
				}

				.wine-info {
					display: flex;
					align-items: center;
					gap: 20rpx;
					
					.wine-type {
						font-size: 28rpx;
						color: #333;
						font-weight: 500;
					}
					
					.quantity-edit {
						display: flex;
						align-items: center;
						gap: 10rpx;
						
						.quantity-text {
							font-size: 28rpx;
							color: #333;
							font-weight: 500;
						}
						
						.unit {
							font-size: 28rpx;
							color: #666;
						}
					}
				}
			}

			.edit-btn {
				position: absolute;
				right: 10rpx;
				bottom: 10rpx;
				padding: 8rpx 20rpx;
				background-color: #409eff;
				color: #fff;
				border-radius: 20rpx;
				font-size: 22rpx;
				border: none;
				transition: all 0.3s;
				z-index: 10;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
				line-height: 1.2;
				min-height: auto;

				&.edit-btn-hover {
					background-color: #3a8ee6;
					transform: scale(0.95);
				}

				&.save-btn {
					background-color: #67c23a;

					&.edit-btn-hover {
						background-color: #5daf34;
					}
				}

				&:disabled {
					background-color: #a0cfff;
				}
			}
		}
	}
}

.loading, .no-data {
	text-align: center;
	padding: 30rpx;
	color: #999;
	font-size: 28rpx;
}

.edit-form, .return-wine-form {
	padding: 20rpx;

	.form-item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;

		.label {
			width: 160rpx;
			font-size: 28rpx;
			color: #666;
		}

		.value {
			flex: 1;
			font-size: 28rpx;
			color: #333;
		}

		.input {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
			background-color: #f5f7fa;
		}

		.picker {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			background-color: #f5f7fa;
		}

		.picker-text {
			height: 70rpx;
			line-height: 70rpx;
			color: #333;
		}
	}
}

.picker {
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	padding: 0 20rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
}



/* 查询区域样式 */
.search-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

	.search-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.search-item {
		display: flex;
		align-items: center;
		margin-bottom: 25rpx;

		.search-label {
			width: 120rpx;
			font-size: 28rpx;
			color: #555;
			flex-shrink: 0;
		}

		.search-input, .date-picker {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 8rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
			background-color: #f5f7fa;
			box-sizing: border-box;
		}

		.picker-text {
			height: 70rpx;
			line-height: 70rpx;
			color: #333;
		}
	}

	.search-buttons {
		display: flex;
		gap: 20rpx;
		margin-top: 30rpx;

		.search-btn, .reset-btn {
			flex: 1;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			font-size: 28rpx;
			border: none;
		}

		.search-btn {
			background-color: #409eff;
			color: #fff;

			&:active {
				background-color: #3a8ee6;
			}
		}

		.reset-btn {
			background-color: #f5f7fa;
			color: #666;
			border: 1rpx solid #dcdfe6;

			&:active {
				background-color: #e9ecef;
			}
		}
	}
}
</style>
